<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>角色管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <style>
        .layui-btn-warm {
            background-color: #FFB800;
            color: #fff;
        }
    </style>
</head>

<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <!-- 搜索表单 -->
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">角色名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn">
                                <i class="layui-icon"></i> 搜 索
                            </button>
                            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="resetSearchBtn">
                                <i class="layui-icon">ဂ</i> 重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <!-- 工具栏 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="add">添加角色</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="deleteBatch">批量删除</button>
            </div>
        </script>

        <!-- 表格容器 -->
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <!-- 表格操作按钮模板 -->
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
            <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="authorize">授权</a>
        </script>

        <!-- 添加/编辑角色弹窗 -->
        <div id="roleEdit" style="display: none; padding: 20px;">
            <form class="layui-form" lay-filter="roleForm">
                <input type="hidden" name="roleId">
                <div class="layui-form-item">
                    <label class="layui-form-label">角色名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="roleName" required lay-verify="required" placeholder="请输入角色名称"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色描述</label>
                    <div class="layui-input-block">
                        <textarea name="mark" placeholder="请输入角色描述" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="saveRole">保存</button>
                    </div>
                </div>
            </form>
        </div>
        <!-- 角色授权弹窗 -->
        <div id="roleAuthorize" style="display: none; padding: 20px;">
            <input type="hidden" id="authorizeRoleId">
            <div class="layui-form-item">
                <div class="layui-btn-group">
                    <button class="layui-btn layui-btn-sm" id="checkAll">全部勾选</button>
                    <button class="layui-btn layui-btn-sm" id="uncheckAll">取消全选</button>
                    <button class="layui-btn layui-btn-sm" id="expandAll">展开所有</button>
                    <button class="layui-btn layui-btn-sm" id="collapseAll">合并所有</button>
                    <button class="layui-btn layui-btn-sm" id="parentChildLink">父子关联</button>
                    <button class="layui-btn layui-btn-sm" id="cancelLink">取消关联</button>
                </div>
            </div>
            <div class="layui-form-item">
                <ul id="menuTree" class="layui-tree" lay-filter="menuTree"></ul>
            </div>
            <div class="layui-form-item">
                <button class="layui-btn" lay-event="saveAuthorize">保存授权</button>
            </div>
        </div>
    </div>
</div>
<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'tree'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer,
            tree = layui.tree;

        // 初始化表格
        table.render({
            elem: '#currentTableId',
            url: '/role/queryPage',
            method: 'post',
            contentType: 'application/json',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                { type: "checkbox", width: 50 },
                { field: 'roleId', width: 80, title: 'ID', sort: true },
                { field: 'roleName', width: 150, title: '角色名称' },
                { field: 'mark', title: '角色描述' },
                { title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center" }
            ]],
            limits: [10, 20, 50],
            limit: 10,
            page: true,
            skin: 'line',
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.list
                };
            },
            response: {
                statusName: 'code',
                statusCode: 0,
                msgName: 'msg',
                countName: 'count',
                dataName: 'data'
            }
        });

        // 搜索功能
        form.on('submit(data-search-btn)', function (data) {
            table.reload('currentTableId', {
                page: { curr: 1 },
                where: {
                    name: data.field.name
                }
            });

            return false;
        });
        //重置
        $('#resetSearchBtn').on('click', function () {
            table.reload('currentTableId', {
                page: { curr: 1 },
                where: {
                    name: ''
                }
            });
        });

        // 工具栏事件监听
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {
                // 添加角色
                form.val('roleForm', {
                    roleId: '',
                    roleName: '',
                    mark: ''
                });
                layer.open({
                    title: '添加角色',
                    type: 1,
                    area: ['500px', '300px'],
                    content: $('#roleEdit')
                });
            } else if (obj.event === 'deleteBatch') {
                // 获取选中行
                var checkStatus = table.checkStatus('currentTableId');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要删除的角色');
                    return;
                }
                // 提取角色ID数组
                var roleIds = checkStatus.data.map(item => item.roleId);
                // 确认删除
                layer.confirm('确定删除选中的角色吗？', function () {
                    $.ajax({
                        url: '/role/deleteIds', // 假设后端批量删除接口
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(roleIds),
                        success: function (res) {
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                table.reload('currentTableId'); // 刷新表格
                            } else {
                                layer.msg('删除失败: ' + res.msg);
                            }
                        }
                    });
                });
            }
        });

        // 行工具事件监听
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                // 编辑角色
                form.val('roleForm', {
                    roleId: data.roleId,
                    roleName: data.roleName,
                    mark: data.mark
                });
                layer.open({
                    title: '编辑角色',
                    type: 1,
                    area: ['500px', '300px'],
                    content: $('#roleEdit')
                });
            } else if (obj.event === 'delete') {
                // 删除角色
                layer.confirm('确定删除该角色吗？', function () {
                    $.ajax({
                        url: '/role/delete/' + data.roleId,
                        type: 'GET',
                        success: function (res) {
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                obj.del();
                            } else {
                                layer.msg('删除失败: ' + res.msg);
                            }
                        }
                    });
                });
            } else if (obj.event === 'authorize') {
                // 打开授权弹窗
                $('#authorizeRoleId').val(data.roleId);
                layer.open({
                    title: '角色授权',
                    type: 1,
                    area: ['600px', '500px'],
                    content: $('#roleAuthorize'),
                    success: function () {
                        loadMenuTree(data.roleId);
                    }
                });
            }
        });

        // 保存角色
        form.on('submit(saveRole)', function (data) {
            var method = data.field.roleId ? 'update' : 'add';
            $.ajax({
                url: '/role/' + method,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg('保存成功');
                        layer.closeAll();
                        table.reload('currentTableId');
                    } else {
                        layer.msg('保存失败: ' + res.msg);
                    }
                }
            });
            return false;
        });

        let cachedTreeData = null;
        let isParentChildLinked = true; // 默认启用父子关联
        let checkedIds= [];

        function loadMenuTree(roleId) {
            $.get('/menu/getAllMenu', function (menuData) {
                $.get('/role/queryMenu/' + roleId, function (res) {
                    // 渲染树组件
                    cachedTreeData = menuData.data;
                    checkedIds = res.data.map(item => item);

                    tree.render({
                        elem: '#menuTree',
                        data: menuData.data,
                        showCheckbox: true,
                        id: 'menuTreeId',
                        checkboxName: 'menuIds',
                        checkChild: false,
                    });
                    tree.setChecked('menuTreeId', checkedIds);
                });
            });
        }

        // 全选
        $('#checkAll').on('click', function () {
            $('#menuTree input[type="checkbox"]').prop('checked', true);
            form.render('checkbox');
        });

        // 取消全选
        $('#uncheckAll').on('click', function () {
            $('#menuTree input[type="checkbox"]').prop('checked', false);
            form.render('checkbox');
        });
        //递归将所有节点的某属性属性设置为指定值
        function setRecursive(nodes, Value) {
            const stack = [...nodes];

            while (stack.length > 0) {
                const node = stack.pop();
                node.spread = Value;

                if (node.children && node.children.length > 0) {
                    // 将子节点压入栈中，后续处理
                    stack.push(...node.children);
                }
            }
        }

        // 展开所有
        $('#expandAll').on('click', function () {
            if (!cachedTreeData) return;

            const dataCopy = JSON.parse(JSON.stringify(cachedTreeData));
            setRecursive(dataCopy, true);
            tree.reload('menuTreeId',{
                data: dataCopy,
            })
            tree.setChecked('menuTreeId', checkedIds);
        });

        // 收起所有
        $('#collapseAll').on('click', function () {
            if (!cachedTreeData) return;
            const dataCopy = JSON.parse(JSON.stringify(cachedTreeData));
            setRecursive(dataCopy, false);
            tree.reload('menuTreeId',{
                data: dataCopy,
            })
            tree.setChecked('menuTreeId', checkedIds);
        });

        // 父子关联按钮
        $('#parentChildLink').on('click', function () {
            isParentChildLinked = true;
            tree.reload('menuTreeId',{
                checkChild:  isParentChildLinked
            })
            layer.msg('已启用父子关联');
        });

        // 取消关联按钮
        $('#cancelLink').on('click', function () {
            isParentChildLinked = false;
            tree.reload('menuTreeId',{
                checkChild:  isParentChildLinked
            })
            layer.msg('已取消父子关联');
            tree.setChecked('menuTreeId', checkedIds);
        });

        // 保存授权
        $(document).on('click', 'button[lay-event="saveAuthorize"]', function () {
            const roleId = $('#authorizeRoleId').val();
            console.log('角色ID:', roleId);

            try {
                const checkedData = tree.getChecked('menuTreeId');
                const menuIds = [];
                function collectIds(data) {
                    data.forEach(item => {
                        menuIds.push(item.id);
                        if (item.children && item.children.length) collectIds(item.children);
                    });
                }
                collectIds(checkedData);

                $.ajax({
                    url: '/role/saveMenuAuth',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ roleId: roleId, menuIds: menuIds }),
                    success: function (res) {
                        if (res.code === 0) {
                            layer.msg('授权成功');
                            layer.closeAll();
                        } else {
                            layer.msg('授权失败: ' + res.msg);
                        }
                    }
                });
            } catch (e) {
                console.error('授权失败:', e);
                layer.msg('授权异常，请查看控制台日志');
            }
        });

    });
</script>
</body>

</html>